package org.misty.seckill.rabbitmq;

import org.misty.seckill.redis.GoodsKey;
import org.misty.seckill.redis.RedisService;
import org.misty.seckill.service.GoodsService;
import org.misty.seckill.service.SeckillService;
import org.misty.seckill.status.SeckillCode;
import org.misty.seckill.util.JSONUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;

@Service
public class MqReceiver {
  private static final Logger LOGGER = LoggerFactory.getLogger(MqReceiver.class);

  @Autowired
  private GoodsService goodsService;
  @Autowired
  private SeckillService seckillService;
  @Autowired
  private RedisService redisService;

  @RabbitListener(queues = {Queues.SECKILL})
  public void receive(String message) {
    LOGGER.info("message received: {}", message);
    var msg = JSONUtil.parse(message, SeckillMessage.class);
    if (msg == null) return;
    var sid = msg.getSGoodsId();
    if (sid == 0) return;
    var user = msg.getUser();
    var qid = msg.getQueuingId();
    var goods = goodsService.getDetailBySid(sid);
    var key = GoodsKey.queuingKey(user.getId(), qid);
    int code = 0;
    long orderId = 0;
    if (goods == null || goods.getStock() <= 0) {
      code = SeckillCode.NOT_ENOUGH;
    } else {
      try {
        var order = seckillService.seckill(user, goods);
        if (order != null) {
          code = SeckillCode.SUCCESS;
          orderId = order.getId();
        } else {
          code = SeckillCode.NOT_ENOUGH;
        }
      } catch (DuplicateKeyException e) {
        code = SeckillCode.DUPLICATE;
      } catch (Exception e) {
        LOGGER.error("", e);
      }
    }
    var value = code + "|" + orderId;
    redisService.set(GoodsKey.SECKILL_QUEUING, key, value);
    if (code != SeckillCode.SUCCESS) {
      seckillService.putAllOnSale(); // TODO
    }
  }



 /* @RabbitListener(queues = {MqConfigurer.QUEUE})
  public void receive(String message) {
    LOGGER.info("message received: {}", message);
  }

  @RabbitListener(queues = {MqConfigurer.TOPIC_1})
  public void receiveTopic1(String message) {
    LOGGER.info("topic 1 received: {}", message);
  }

  @RabbitListener(queues = {MqConfigurer.TOPIC_2})
  public void receiveTopic2(String message) {
    LOGGER.info("topic 2 received: {}", message);
  }

  @RabbitListener(queues = {MqConfigurer.HEADERS_QUEUE})
  public void receiveHeaders(byte[] message) {
    LOGGER.info("header received: {}", new String(message));
  }*/
}
